<template>
  <div class="submit_module_wrap">
    <el-card class="submit_appointment_query_card">
      <!-- 查询表单 -->
      <div class="select_form_box">
        <el-form :inline="true" style="height: 30px" :model="queryAppointmentFormData" class="demo-form-inline">
          <el-form-item>
            <template #label>
              <i class="iconfont icon-xingming" style="font-size: 19px"></i>
              <span>学生姓名</span>
            </template>
            <el-input style="width: 130px" v-model="queryAppointmentFormData.studentName" placeholder="学生姓名" clearable />
          </el-form-item>
          <el-form-item>
            <template #label>
              <i class="iconfont icon-gonghao" style="font-size: 19px"></i>
              <span>学生工号</span>
            </template>
            <el-input style="width: 150px" v-model="queryAppointmentFormData.studentCode" placeholder="学生工号" clearable />
          </el-form-item>

          <el-form-item>
            <template #label>
              <i class="iconfont icon-shijianriqi"></i>
              <span>预约时间</span>
            </template>
            <!-- <el-date-picker
              v-model="queryAppointmentFormData.date"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择预约日期"
              clearable
            /> -->
            <el-date-picker
              v-model="queryAppointmentFormData.date"
              value-format="YYYY-MM-DD HH:mm:ss"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            />
          </el-form-item>

          <el-form-item>
            <template #label>
              <i class="iconfont icon-shiyanshiguanli" style="font-size: 17px"></i>
              <span>实验室房间号</span>
            </template>
            <el-input
              style="width: 144px"
              v-model="queryAppointmentFormData.reservationHome"
              placeholder="实验室房间号"
              clearable
            />

            <!-- <el-select
              v-model="queryAppointmentFormData.reservationHome"
              filterable
              placeholder="请选择"
              style="width: 120px"
              clearable
            >
              <el-option v-for="(ll, indexL) in labList" :key="indexL" :label="ll.laboratoryHome" :value="ll.laboratoryHome" />
            </el-select> -->
          </el-form-item>

          <el-form-item>
            <template #label>
              <i class="iconfont icon-yiqihecha" style="font-size: 19px"></i>
              <span>预约仪器</span>
            </template>
            <el-input style="width: 200px" v-model="queryAppointmentFormData.reservationDev" placeholder="预约仪器" clearable />
            <!-- <el-select
              v-model="queryAppointmentFormData.reservationDev"
              filterable
              placeholder="请选择仪器"
              style="width: 220px"
              clearable
            >
              <el-option v-for="(dl, indexD) in devList" :key="indexD" :label="dl.label" :value="dl.value" />
            </el-select> -->
          </el-form-item>

          <el-form-item>
            <template #label>
              <i class="iconfont icon-shenhe" style="font-size: 17px"></i>
              <span>审核状态</span>
            </template>
            <!-- <el-input style="width: 200px" v-model="queryAppointmentFormData.studentCode" placeholder="学生工号" clearable /> -->
            <el-select
              v-model="queryAppointmentFormData.checkResult"
              filterable
              placeholder="请选择状态"
              style="width: 120px"
              clearable
            >
              <el-option v-for="(csl, indexC) in checkStatusList" :key="indexC" :label="csl.label" :value="csl.value" />
            </el-select>
          </el-form-item>

          <el-form-item style="margin-right: 20px">
            <el-button type="primary" :icon="Search" @click="selectAppointmentClick">查询</el-button>
            <!-- 操作按钮 -->
            <div class="action_box">
              <el-button type="success" :icon="Promotion" @click="sendAppointmentClick">发起预约</el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>

    <!-- 表格卡片 -->
    <el-card class="appoint_table_card">
      <!-- size="small" -->
      <el-table style="width: 100%" :data="appointList" :loading="isAppointListLoading" stripe :scrollbar-always-on="true">
        <el-table-column prop="studentName" label="学生姓名" align="center" width="80" />
        <el-table-column prop="studentCode" label="学生工号" width="140" align="center" />
        <el-table-column prop="studentPhone" label="学生手机号" width="100" align="center" />
        <el-table-column prop="startTime" label="开始时间" align="center" width="180" />
        <el-table-column prop="endTime" label="结束时间" align="center" width="180" />

        <el-table-column prop="reservationHome" label="房间号" align="center" width="120" />
        <el-table-column prop="reservationDev" label="预约仪器" align="center" width="180"> </el-table-column>
        <el-table-column prop="chemicalsAppointUses" label="化学药品" align="center">
          <template #default="scope">
            <el-link
              v-if="
                scope.row.chemicalDrugs != '' &&
                scope.row.chemicalDrugs != null &&
                scope.row.chemicalDrugs != undefined &&
                scope.row.chemicalDrugs.length != 0
              "
              type="primary"
              class="look_link"
              @click="lookDrugClick(scope.row)"
            >
              <i class="iconfont icon-ziyuan"></i>
              <span class="look_link_text">查看药品</span>
            </el-link>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="experimentalSchemeDocs" label="实验方案" align="center">
          <template #default="scope">
            <el-link
              v-if="
                scope.row.experimentFileUrl != '' &&
                scope.row.experimentFileUrl != null &&
                scope.row.experimentFileUrl != undefined
              "
              type="primary"
              class="look_link"
              @click="lookDocClick(scope.row)"
            >
              <i class="iconfont icon-wenjian"></i>
              <span class="look_link_text">下载文档</span>
            </el-link>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="studentType" label="学生类型" width="80" align="center" />
        <el-table-column prop="experimentType" label="实验类型" width="80" align="center" />
        <el-table-column prop="mentorName" label="导师姓名" align="center" width="80" />
        <el-table-column prop="sameGroupStudents" label="学生名单" align="center">
          <template #default="scope">
            <el-link
              v-if="
                scope.row.allStudent != '' &&
                scope.row.allStudent != null &&
                scope.row.allStudent != undefined &&
                scope.row.allStudent.length != 0
              "
              type="primary"
              class="look_link"
              @click="lookStudentsClick(scope.row)"
            >
              <i class="iconfont icon-view-people"></i>
              <span class="look_link_text">查看名单</span>
            </el-link>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.checkResult == 0" type="warning">待审核</el-tag>
            <el-popover
              popper-class="check_popper"
              class="box-item"
              v-if="scope.row.checkResult == 1"
              title=""
              placement="top-start"
            >
              <template #reference>
                <el-tag style="cursor: pointer" type="success">通过</el-tag>
              </template>

              <CheckInfo :people="scope.row.checkPeople" :time="scope.row.checkTime" :desc="scope.row.checkDesc" />
            </el-popover>

            <el-popover
              popper-class="check_popper"
              v-if="scope.row.checkResult == 2"
              class="box-item"
              title=""
              :content="scope.row.checkDesc"
              placement="top-start"
            >
              <template #reference>
                <el-tag style="cursor: pointer" type="danger">不通过</el-tag>
              </template>
              <CheckInfo :people="scope.row.checkPeople" :time="scope.row.checkTime" :desc="scope.row.checkDesc" />
            </el-popover>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination_box">
        <el-pagination
          class="tab_pagination"
          background
          layout="prev, pager, next"
          v-model:current-page="queryAppointmentFormData.page"
          v-model:page-size="queryAppointmentFormData.size"
          :total="tableTotal"
          @change="paginationChange"
        />
      </div>
    </el-card>

    <!-- 查看化学药品预约使用名单弹窗 -->
    <el-dialog
      v-model="isShowLookChemicalDrugsDialog"
      title="化学药品预约使用名单"
      width="800"
      @close="lookChemicalDrugsDialogCloseClick"
    >
      <div class="look_chemical_dialog_box">
        <el-table :data="currentShowLookChemicalDrugs" border stripe size="small" style="width: 100%">
          <el-table-column property="num" label="序号" bordered width="80" align="center">
            <template #default="scope">
              <span>{{ scope.row.num + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column property="chemicalName" label="药品名称" align="center" />
        </el-table>
        <div class="look_chemical_dialog_pagination_box">
          <el-pagination
            size="small"
            class="tab_pagination"
            background
            layout="prev, pager, next"
            v-model:current-page="currentLookChemicalDrugsPage"
            :page-size="10"
            :total="currentLookChemicalDrugs.length"
            @change="lookChemicalPaginationChange"
          />
        </div>
      </div>
    </el-dialog>
    <!-- 
    
    仪器1,仪器2,仪器3,仪器4,仪器5,仪器6,仪器7,仪器8,仪器9,仪器10,仪器11,仪器12
    -->

    <!-- 查看学生名单弹窗 -->
    <el-dialog v-model="isShowLookAllStudentDialog" title="学生名单" width="800" @close="lookAllStudentDialogCloseClick">
      <div class="look_chemical_dialog_box">
        <el-table :data="currentShowLookAllStudent" border stripe size="small" style="width: 100%">
          <el-table-column property="num" label="序号" bordered width="80" align="center">
            <template #default="scope">
              <span>{{ scope.row.num + 1 }}</span>
            </template>
          </el-table-column>
          <el-table-column property="studentNum" label="学号" align="center" />
          <el-table-column property="studentName" label="姓名" align="center" />
          <el-table-column property="studentPhone" label="手机号" align="center" />
        </el-table>
        <div class="look_chemical_dialog_pagination_box">
          <el-pagination
            size="small"
            class="tab_pagination"
            background
            layout="prev, pager, next"
            v-model:current-page="currentLookAllStudentPage"
            :page-size="10"
            :total="currentLookAllStudent.length"
            @change="lookAllStudentPaginationChange"
          />
        </div>
      </div>
    </el-dialog>

    <!-- 发起预约弹窗 -->
    <el-dialog
      style="width: 1876px; height: 872px; margin-top: 20px; margin-bottom: 0px"
      v-model="isShowSendAppointmentFormDialog"
      draggable
      @close="sendAppointDialogClose"
      destroy-on-close
    >
      <template #header>
        <div class="send_appoint_dialog_header_box">
          <el-icon class="send_appoint_icon" size="18"><Promotion /></el-icon>
          <span class="title_text">发起新预约</span>
        </div>
      </template>
      <div class="send_appoint_dialog_content_box">
        <div class="top_box">
          <el-form
            :inline="true"
            :model="sendAppointmentFormData"
            :rules="sendAppointFormRules"
            ref="sendAppointFormRef"
            class="demo-form-inline"
          >
            <el-form-item label="学生工号" prop="studentCode">
              <el-input
                v-model="sendAppointmentFormData.studentCode"
                placeholder="请输入学生工号"
                style="width: 150px"
                clearable
              />
            </el-form-item>
            <el-form-item label="学生姓名" prop="studentName">
              <el-input
                v-model="sendAppointmentFormData.studentName"
                placeholder="请输入学生姓名"
                style="width: 120px"
                clearable
              />
            </el-form-item>
            <el-form-item label="学生手机号" prop="studentPhone">
              <el-input
                v-model="sendAppointmentFormData.studentPhone"
                placeholder="请输入学生手机号"
                style="width: 136px"
                clearable
              />
            </el-form-item>
            <el-form-item label="实验室房间号" prop="reservationHome">
              <el-input
                v-model="sendAppointmentFormData.reservationHome"
                placeholder="请输入实验室房间号"
                style="width: 168px"
                clearable
              />
              <!-- <el-select
                v-model="sendAppointmentFormData.reservationHome"
                placeholder="请选择实验室房间号"
                style="width: 180px"
                clearable
                filterable
              >
                <el-option v-for="(ll, indexL) in labList" :key="indexL" :label="ll.laboratoryHome" :value="ll.laboratoryHome" />
              </el-select> -->
            </el-form-item>
            <el-form-item label="预约仪器" prop="reservationDev">
              <el-input
                v-model="sendAppointmentFormData.reservationDev"
                placeholder="请输入预约仪器"
                style="width: 168px"
                clearable
              />
              <!-- <el-select
                v-model="sendAppointmentFormData.reservationDev"
                placeholder="请选择仪器"
                clearable
                filterable
                style="width: 180px"
              >
                <el-option v-for="(dl, indexD) in devList" :key="indexD" :label="dl.label" :value="dl.value" />
              </el-select> -->
            </el-form-item>
            <el-form-item label="学生类型" prop="studentType">
              <el-radio-group v-model="sendAppointmentFormData.studentType">
                <el-radio value="本科">本科</el-radio>
                <el-radio value="研究生">研究生</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item style="margin-left: 6px" label="实验类型" prop="experimentType">
              <el-radio-group v-model="sendAppointmentFormData.experimentType">
                <el-radio value="教学">教学</el-radio>
                <el-radio value="科研">科研</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="预约时间" prop="date">
              <el-date-picker
                v-model="sendAppointmentFormData.date"
                type="datetimerange"
                value-format="YYYY-MM-DD HH:mm:ss"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>

            <el-form-item style="margin-left: 4px" label="导师姓名" prop="mentorName">
              <el-input
                v-model="sendAppointmentFormData.mentorName"
                placeholder="请输入导师姓名"
                style="width: 136px"
                clearable
              />
            </el-form-item>
          </el-form>
        </div>
        <div class="bottom_box">
          <!-- 化学药品预约使用名单 -->
          <div class="chemical_drugs_box">
            <div class="title_box">
              <i class="iconfont icon-shiji"></i>
              <span class="title_text">化学药品预约使用名单</span>
            </div>
            <div class="import_chemical_box">
              <input type="file" @change="chemicalSelectImportChange" />
              <el-button class="btn" type="success" size="small" @click="downChemicalExcelClick">下载模板</el-button>
              <el-button class="btn" type="primary" size="small" @click="parseChemicalTempImportClick">解析文件</el-button>
            </div>
            <el-divider style="margin: 8px 0px" />
            <div class="list_header_box" v-if="sendAppointmentFormData.chemicalDrugs.length != 0">
              <span>药品名称</span>
            </div>
            <div class="list_box" v-if="sendAppointmentFormData.chemicalDrugs.length != 0">
              <div class="list_item_box" v-for="(cd, indexC) in sendAppointmentFormData.chemicalDrugs" :key="indexC">
                <span v-if="!cd.isEdit" class="value">
                  {{ cd.chemicalName }}
                </span>
                <el-input v-else v-model="cd.chemicalName" />
                <div class="action_box">
                  <!-- 保存 -->
                  <el-button
                    v-if="cd.isEdit"
                    :icon="Check"
                    type="success"
                    plain
                    circle
                    size="small"
                    @click="chemicalSaveClick(cd)"
                  />

                  <!-- 编辑 -->
                  <el-button v-else :icon="Edit" type="primary" plain circle size="small" @click="chemicalEditClick(cd)" />
                  <!-- 删除 -->
                  <el-button
                    style="margin-left: 8px"
                    :icon="Delete"
                    type="danger"
                    plain
                    circle
                    size="small"
                    @click="chemicalDelClick(cd)"
                  />
                </div>
              </div>
              <div class="add_box">
                <el-button style="width: 100%" @click="addChemical" :icon="Plus" />
              </div>
            </div>
            <div class="not_data_box" v-else>
              <el-empty description="暂无数据" :image-size="100">
                <el-button :icon="Plus" @click="addChemical">添加药品</el-button>
              </el-empty>
            </div>
          </div>

          <!-- 同组学生名单 -->
          <div class="all_student_box">
            <div class="title_box">
              <i class="iconfont icon-xueshengmingdan"></i>
              <span class="title_text">同组学生名单</span>
            </div>
            <div class="import_student_box">
              <input type="file" @change="studentSelectImportChange" />
              <div>
                <el-button class="btn" type="success" size="small" @click="downStudentExcelClick">下载模板</el-button>
                <el-button class="btn" type="primary" size="small" @click="parseStudentTempImportClick">解析文件</el-button>
              </div>
            </div>
            <el-divider style="margin: 8px 0px" />
            <div class="list_header_box" v-if="sendAppointmentFormData.allStudent.length != 0">
              <span class="code">学号</span>
              <span class="name">学生姓名</span>
              <span class="phone">手机号</span>
            </div>
            <div class="list_box" v-if="sendAppointmentFormData.allStudent.length != 0">
              <div class="list_item_box" v-for="(as, indexA) in sendAppointmentFormData.allStudent" :key="indexA">
                <!-- 学号 -->
                <span v-if="!as.isEdit" class="code">
                  {{ as.studentCode }}
                </span>
                <el-input v-else v-model="as.studentCode" style="width: 170px" />

                <!-- 学生姓名 -->
                <span v-if="!as.isEdit" class="name">
                  {{ as.studentName }}
                </span>
                <el-input v-else v-model="as.studentName" style="width: 170px" />

                <!-- 手机号 -->
                <span v-if="!as.isEdit" class="phone">
                  {{ as.studentPhone }}
                </span>
                <el-input v-else v-model="as.studentPhone" style="width: 180px" />

                <div class="action_box">
                  <!-- 保存 -->
                  <el-button
                    v-if="as.isEdit"
                    :icon="Check"
                    type="success"
                    plain
                    circle
                    size="small"
                    @click="studentSaveClick(as)"
                  />

                  <!-- 编辑 -->
                  <el-button v-else :icon="Edit" type="primary" plain circle size="small" @click="studentEditClick(as)" />
                  <!-- 删除 -->
                  <el-button
                    style="margin-left: 8px"
                    :icon="Delete"
                    type="danger"
                    plain
                    circle
                    size="small"
                    @click="studentDelClick(as)"
                  />
                </div>
              </div>
              <div class="add_box">
                <el-button style="width: 100%" @click="addStudent" :icon="Plus" />
              </div>
            </div>
            <div class="not_data_box" v-else>
              <el-empty description="暂无数据" :image-size="100">
                <el-button :icon="Plus" @click="addStudent">添加学生</el-button>
              </el-empty>
            </div>
          </div>

          <!-- 上传文件 -->
          <div class="upload_file_box">
            <div class="title_box">
              <i class="iconfont icon-dingdanzhuangtai"></i>
              <span class="title_text">实验方案文档</span>
            </div>
            <el-divider style="margin: 8px 0px" />
            <div>
              <el-upload
                class="upload-demo"
                drag
                :action="uploadFileUrl"
                :on-success="uploadExperimentalSchemeDocSuccess"
                :on-remove="uploadExperimentalSchemeDocRemove"
                :limit="1"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">将文件拖拽至此处或点击此处选择文件上传</div>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="sendAppointDialogCancelClick">取消</el-button>
          <el-button type="primary" @click="sendAppointDialogConfirmClick"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted, reactive, ref } from "vue";
import { Search, Promotion, Plus, Delete, Check, Edit } from "@element-plus/icons-vue";
import "./index.scss";
export default defineComponent({
  name: "SubmitModule"
});
</script>
<script lang="ts" setup>
import { AppointItemType, AppointListType } from "@/api/modules/appointment/type";
import { labListType } from "@/views/laboratoryList/type";
// import { instrumentListType } from "@/views/instrumentList/type";
import _ from "lodash";
import { uploadFileUrl } from "@/api/modules/appointment/index.ts";
import { selectAllLabApi } from "@/api/modules/laboratoryList/index";
// import { selectAllDevApi } from "@/api/modules/instrumentList/index";
import { selectByPageApi, addReservationApi } from "@/api/modules/appointment/index";
import { ElMessage } from "element-plus";
import { v4 as uuidv4 } from "uuid";
import CheckInfo from "../checkInfo/index.vue";
import { chemicalImportTempUrl, studentImportTempUrl } from "@/libs/down";
import * as XLSX from "xlsx";
// import StudentExcel from "./student.xlsx";

// 药品名单文件数据
const chemicalFileData = ref(null);

// 学生名单文件数据
const studentFileData = ref(null);

// 下载药品名单模板点击事件
const downChemicalExcelClick = () => {
  window.open(chemicalImportTempUrl);
};

// 下载学生名单模板点击事件
const downStudentExcelClick = () => {
  window.open(studentImportTempUrl);
};

// 药品名单选择文件change事件
const chemicalSelectImportChange = () => {
  const files = event.target.files;
  if (files.length === 0) return;
  const file = files[0];
  const reader = new FileReader();
  reader.onload = e => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // header: 1 表示第一行作为头部信息
    console.log(jsonData); // 这里你可以看到解析后的JSON数据
    chemicalFileData.value = jsonData;
  };
  reader.readAsArrayBuffer(file);
};

// 学生名单选择文件 change 事件
const studentSelectImportChange = () => {
  const files = event.target.files;
  if (files.length === 0) return;
  const file = files[0];
  const reader = new FileReader();
  reader.onload = e => {
    const data = new Uint8Array(e.target.result);
    const workbook = XLSX.read(data, { type: "array" });
    const firstSheetName = workbook.SheetNames[0];
    const worksheet = workbook.Sheets[firstSheetName];
    const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 }); // header: 1 表示第一行作为头部信息
    console.log(jsonData); // 这里你可以看到解析后的JSON数据
    studentFileData.value = jsonData;
  };
  reader.readAsArrayBuffer(file);
};

// 解析药品名单模板导入点击事件
const parseChemicalTempImportClick = () => {
  if (chemicalFileData.value == null || chemicalFileData.value == undefined) {
    ElMessage.error("请点击左侧选择文件进行文件选择");
    return;
  }

  console.log("#解析数据", chemicalFileData.value);

  // 判断文件数据是否为空
  if (chemicalFileData.value.length < 2) {
    ElMessage.error("解析错误,数据不完整");
    return;
  }

  // 判断字段是否正确
  if (chemicalFileData.value[0].length != 1) {
    ElMessage.error("解析错误,字段错误");
    return;
  }

  // 开始解析
  let newChemicalDrugs = [];
  chemicalFileData.value.forEach((item, index) => {
    if (index != 0) {
      newChemicalDrugs.push({
        cid: uuidv4(),
        isEdit: false,
        chemicalName: item[0]
      });
    }
  });

  sendAppointmentFormData.value.chemicalDrugs = newChemicalDrugs;
};

// 解析学生名单模板导入点击事件
const parseStudentTempImportClick = () => {
  if (studentFileData.value == null || studentFileData.value == undefined) {
    ElMessage.error("请点击左侧选择文件进行文件选择");
    return;
  }

  console.log("#解析数据", studentFileData.value);

  // 判断文件数据是否为空
  if (studentFileData.value.length < 2) {
    ElMessage.error("解析错误,数据不完整");
    return;
  }

  // 判断字段是否正确
  if (studentFileData.value[0].length != 3) {
    ElMessage.error("解析错误,字段错误");
    return;
  }

  // 开始解析
  let newStudent = [];
  // sendAppointmentFormData.allStudent

  studentFileData.value.forEach((item, index) => {
    if (index != 0) {
      newStudent.push({
        sid: uuidv4(),
        isEdit: false,
        studentName: item[1],
        studentCode: item[0],
        studentPhone: item[2]
      });
    }
  });

  sendAppointmentFormData.value.allStudent = newStudent;
};

//  学生编辑点击事件
const studentEditClick = row => {
  sendAppointmentFormData.value.allStudent.forEach(item => {
    if (item.sid == row.sid) {
      item.isEdit = true;
    }
  });
};

// 删除学生点击事件
const studentDelClick = row => {
  console.log(row.sid);
  sendAppointmentFormData.value.allStudent = sendAppointmentFormData.value.allStudent.filter(item => {
    return item.sid != row.sid;
  });
};

// 学生保存点击事件
const studentSaveClick = row => {
  if (isNotNullStr(row.studentCode) && isNotNullStr(row.studentName) && isNotNullStr(row.studentPhone)) {
    sendAppointmentFormData.value.allStudent.forEach(item => {
      if (item.cid == row.cid) {
        item.isEdit = false;
      }
    });
  } else {
    ElMessage.error("请将信息填写完整!");
  }
};

// 添加学生点击事件
const addStudent = () => {
  // 先判断上一个是否填写
  if (sendAppointmentFormData.value.allStudent.length != 0) {
    let lastStudent = sendAppointmentFormData.value.allStudent[sendAppointmentFormData.value.allStudent.length - 1];
    if (
      isNotNullStr(lastStudent.studentName) &&
      isNotNullStr(lastStudent.studentCode) &&
      isNotNullStr(lastStudent.studentPhone)
    ) {
      sendAppointmentFormData.value.allStudent.forEach(item => {
        item.isEdit = false;
      });
      sendAppointmentFormData.value.allStudent.push({
        sid: uuidv4(),
        isEdit: true,
        studentName: "",
        studentCode: "",
        studentPhone: ""
      });
    } else {
      ElMessage.error("请先填写完整上一个!");
    }
  } else {
    sendAppointmentFormData.value.allStudent.push({
      sid: uuidv4(),
      isEdit: true,
      studentName: "",
      studentCode: "",
      studentPhone: ""
    });
  }
};

// 药品删除点击事件
const chemicalDelClick = row => {
  console.log(row.cid);
  sendAppointmentFormData.value.chemicalDrugs = sendAppointmentFormData.value.chemicalDrugs.filter(item => {
    return item.cid != row.cid;
  });
};

// 药品编辑点击事件
const chemicalEditClick = row => {
  sendAppointmentFormData.value.chemicalDrugs.forEach(item => {
    if (item.cid == row.cid) {
      item.isEdit = true;
    }
  });
};

// 药品保存点击事件
const chemicalSaveClick = row => {
  if (isNotNullStr(row.chemicalName)) {
    sendAppointmentFormData.value.chemicalDrugs.forEach(item => {
      if (item.cid == row.cid) {
        item.isEdit = false;
      }
    });
  } else {
    ElMessage.error("请将信息填写完整!");
  }
};

// 判断是否等于空
const isNotNullStr = str => {
  return str != "" && str != null && str != undefined ? true : false;
};

// 添加药品点击事件
const addChemical = () => {
  // 先判断上一个是否填写
  if (sendAppointmentFormData.value.chemicalDrugs.length != 0) {
    if (
      isNotNullStr(
        sendAppointmentFormData.value.chemicalDrugs[sendAppointmentFormData.value.chemicalDrugs.length - 1].chemicalName
      )
    ) {
      sendAppointmentFormData.value.chemicalDrugs.forEach(item => {
        item.isEdit = false;
      });
      sendAppointmentFormData.value.chemicalDrugs.push({
        cid: uuidv4(),
        isEdit: true,
        chemicalName: ""
      });
    } else {
      ElMessage.error("请先填写完整上一个!");
    }
  } else {
    sendAppointmentFormData.value.chemicalDrugs.push({
      cid: uuidv4(),
      isEdit: true,
      chemicalName: ""
    });
  }
};

// 发起预约表单数据
const sendAppointmentFormData = ref<AppointItemType>({
  // 预约id
  // reservationId: null,
  // 学生工号
  studentCode: "",
  // 学生姓名
  studentName: "",
  // 学生手机号
  studentPhone: "",
  // 预约实验室房间号
  reservationHome: "",
  // 预约仪器名称
  reservationDev: "",
  // 化学药品预约使用名单
  chemicalDrugs: [],
  // 启动时间
  startTime: "",
  // 结束时间
  endTime: "",
  // 实验方案文档上传
  experimentFileUrl: "",
  // 学生类型
  studentType: "",
  // 实验类型
  experimentType: "",
  // 导师姓名
  mentorName: "",
  // 同组学生名单
  allStudent: [],
  // 时间
  date: []
  // 状态/结果   0 待审核   1 审核通过  2 审核不通过
  // checkResult: 0,
  // 审核人
  // checkPeople: "",
  // 审核备注
  // checkDesc: "",
  // 审核时间
  // checkTime: "",
  // 创建时间
  // createTime: ""
});

// 发起预约表单Ref
const sendAppointFormRef = ref(null);

// 发起预约表单校验规则
const sendAppointFormRules = ref({
  studentCode: [{ required: true, message: "学生工号为必填项", trigger: "blur" }],
  studentName: [{ required: true, message: "学生姓名为必填项", trigger: "blur" }],
  studentPhone: [{ required: true, message: "学生手机号为必填项", trigger: "blur" }],
  reservationHome: [{ required: true, message: "预约实验室房间号为必填项", trigger: "blur" }],
  reservationDev: [{ required: true, message: "预约仪器为必填项", trigger: "blur" }],
  studentType: [{ required: true, message: "学生类型为必选项", trigger: "blur" }],
  experimentType: [{ required: true, message: "实验类型为必选项", trigger: "blur" }],
  mentorName: [{ required: true, message: "导师名称为必填项", trigger: "blur" }],
  date: [{ required: true, message: "请选择时间", trigger: "blur" }]
});

// 是否显示发起预约表单弹窗标识
const isShowSendAppointmentFormDialog = ref(false);

// 预约查询表单数据
const queryAppointmentFormData = reactive({
  // 学生工号
  studentCode: "",
  // 学生姓名
  studentName: "",
  // 开始预约时间
  startReservationDate: "",
  // 结束预约时间
  endReservationDate: "",
  // 预约实验室房间号
  reservationHome: "",
  // 预约仪器
  reservationDev: "",
  // 审核状态
  checkResult: "",
  // 页码
  page: 1,
  // 每页条数
  size: 10,

  // 时间
  date: []
});

// 实验室列表
const labList = ref<labListType>([]);

// 仪器列表
// const devList = ref<instrumentListType>([]);

// 审核状态
const checkStatusList = ref([
  {
    label: "通过",
    value: 1
  },
  {
    label: "不通过",
    value: 2
  },
  {
    label: "待审核",
    value: 0
  }
]);

// 查看名单表格每页条数
const lookTableSize = ref(10);

/* 化学药品预约使用名单 */

// 是否显示化学药品预约使用名单的弹窗标识
const isShowLookChemicalDrugsDialog = ref(false);

// 当前查看药品列表
const currentLookChemicalDrugs = ref([]);

// 当前查看药品表格页码
const currentLookChemicalDrugsPage = ref(1);

// 当前查看药品显示列表
const currentShowLookChemicalDrugs = computed(() => {
  let startIndex = (currentLookChemicalDrugsPage.value - 1) * lookTableSize.value;
  let yData = _.cloneDeep(currentLookChemicalDrugs.value);
  let rData = yData.slice(startIndex, startIndex + 10);
  console.log("rData", startIndex, yData, rData);
  return rData;
});

/* 所有学生名单 */

// 是否显示学生名单的弹窗标识
const isShowLookAllStudentDialog = ref(false);

// 当前查看学生名单列表
const currentLookAllStudent = ref([]);

// 当前查看学生名单表格页码
const currentLookAllStudentPage = ref(1);

// 当前查看学生名单显示列表
const currentShowLookAllStudent = computed(() => {
  let startIndex = (currentLookAllStudentPage.value - 1) * lookTableSize.value;
  let yData = _.cloneDeep(currentLookAllStudent.value);
  let rData = yData.slice(startIndex, startIndex + 10);
  console.log("rData", startIndex, yData, rData);
  return rData;
});

/*

20250414001,王五,13093291267;20250414002,赵六,13093291268;20250414003,孙七,13093291269;20250414001,王五,13093291267;20250414002,赵六,13093291268;20250414003,孙七,13093291269;20250414001,王五,13093291267;20250414002,赵六,13093291268;20250414003,孙七,13093291269;20250414001,王五,13093291267;20250414002,赵六,13093291268;20250414003,孙七,13093291269;20250414001,王五,13093291267;20250414002,赵六,13093291268;20250414003,孙七,13093291269;20250414001,王五,13093291267;20250414002,赵六,13093291268;20250414003,孙七,13093291269

*/

//  预约列表
const appointList = ref<AppointListType>([]);

// 预约表格总条数
const tableTotal = ref(0);

// 预约列表加载标识
const isAppointListLoading = ref(false);

// 发起预约点击事件
const sendAppointmentClick = () => {
  isShowSendAppointmentFormDialog.value = true;
};

// 上传实验方案文档成功函数
const uploadExperimentalSchemeDocSuccess = (res, uploadFile) => {
  if (res.result == "success") {
    sendAppointmentFormData.value.experimentFileUrl = res.data;
  } else if (res.result == "error") {
    message.error("上传文件失败");
  }
};

// 上传实验方案文档删除函数
const uploadExperimentalSchemeDocRemove = res => {
  console.log(res);

  sendAppointmentFormData.value.experimentFileUrl = "";
};

// 发起预约弹窗关闭事件
const sendAppointDialogClose = () => {
  if (!sendAppointFormRef.value) return;
  sendAppointFormRef.value.resetFields();
  resetSendAppointmentFormData();
};

// 拼接药品字符串数据
const joinChemicalStr = (data: { cid: string; isEdit: boolean; chemicalName: string }[]) => {
  let str;
  if (data.length == 0) {
    str = "";
  } else {
    let nArr = [];
    data.forEach(item => {
      nArr.push(item.chemicalName);
    });
    str = nArr.join(",");
  }
  return str;
};

// 拼接学生名单字符串数据
const joinAllStudentStr = (
  data: {
    sid: string;
    isEdit: boolean;
    studentName: string;
    studentCode: string;
    studentPhone: string;
  }[]
) => {
  let str;
  if (data.length == 0) {
    str = "";
  } else {
    let nArr = [];
    data.forEach(item => {
      nArr.push(`${item.studentCode},${item.studentName},${item.studentPhone}`);
    });
    str = nArr.join(";");
  }
  return str;
};

// 发起预约弹窗确定点击事件
const sendAppointDialogConfirmClick = () => {
  if (!sendAppointFormRef.value) return;
  sendAppointFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log(sendAppointmentFormData.value);

      let data = _.cloneDeep(sendAppointmentFormData.value);
      data.startTime = data.date[0];
      data.endTime = data.date[1];
      data.chemicalDrugs = joinChemicalStr(data.chemicalDrugs);
      data.allStudent = joinAllStudentStr(data.allStudent);
      delete data.date;

      console.log("#发起预约提交数据", data);
      sendAppointFunc(data);
    } else {
      console.log("error submit!", fields);
    }
  });
};

// 发起预约函数
const sendAppointFunc = async data => {
  await addReservationApi(data)
    .then(res => {
      if (res.result == "success") {
        ElMessage.success("发起预约成功!");
        isShowSendAppointmentFormDialog.value = false;
        sendAppointFormRef.value.resetFields();
        resetSendAppointmentFormData();
      } else if (res.result == "error") {
        ElMessage.error(res.msg);
      }
    })
    .finally(() => {
      selectByPageFunc();
    });
};

// 重置发起预约表单数据
const resetSendAppointmentFormData = () => {
  sendAppointmentFormData.value = {
    // 预约id
    // reservationId: null,
    // 学生工号
    studentCode: "",
    // 学生姓名
    studentName: "",
    // 学生手机号
    studentPhone: "",
    // 预约实验室房间号
    reservationHome: "",
    // 预约仪器名称
    reservationDev: "",
    // 化学药品预约使用名单
    chemicalDrugs: [],
    // 启动时间
    startTime: "",
    // 结束时间
    endTime: "",
    // 实验方案文档上传
    experimentFileUrl: "",
    // 学生类型
    studentType: "",
    // 实验类型
    experimentType: "",
    // 导师姓名
    mentorName: "",
    // 同组学生名单
    allStudent: [],
    // 时间
    date: []
  };
};

// 发起预约弹窗取消点击事件
const sendAppointDialogCancelClick = () => {
  isShowSendAppointmentFormDialog.value = false;
};

// 查看仪器点击事件
// const lookInstrumentClick = row => {
//   console.log(row);
// };

// 查看药品点击事件
const lookDrugClick = row => {
  currentLookChemicalDrugs.value = _.cloneDeep(row.chemicalDrugs);
  console.log(currentLookChemicalDrugs.value);
  isShowLookChemicalDrugsDialog.value = true;
};

// 查看药品弹窗关闭点击事件
const lookChemicalDrugsDialogCloseClick = () => {
  isShowLookChemicalDrugsDialog.value = false;
};

// 查看药品弹窗表格分页器change事件
const lookChemicalPaginationChange = e => {
  currentLookChemicalDrugsPage.value = e;
};

// 查看文档点击事件
const lookDocClick = row => {
  // console.log(row);
  // window.location.href(row.experimentFileUrl);
  downloadFile(row.experimentFileUrl);
};

function downloadFile(url) {
  const link = document.createElement("a");
  link.href = url;
  // link.download = fileName;
  link.target = "_blank"; // 可选，如果希望在新窗口中下载文件，请取消注释此行
  link.click();
}

// 查看学生名单点击事件
const lookStudentsClick = row => {
  currentLookAllStudent.value = _.cloneDeep(row.allStudent);
  console.log(currentLookAllStudent.value);
  isShowLookAllStudentDialog.value = true;
};

// 查看学生名单弹窗关闭点击事件
const lookAllStudentDialogCloseClick = () => {
  isShowLookAllStudentDialog.value = false;
};

// 查看学生名单表格分页器change事件
const lookAllStudentPaginationChange = e => {
  currentLookAllStudentPage.value = e;
};

// 查询所有实验室
const selectAllLabFunc = async () => {
  await selectAllLabApi().then(res => {
    if (res.result == "success") {
      labList.value = res.data;
    }
  });
};

// 查询所有仪器
// const selectAllDevFunc = async () => {
//   await selectAllDevApi().then(res => {
//     if (res.result == "success") {
//       let nDevList = [];
//       res.data.forEach(item => {
//         nDevList.push({
//           label: `#${item.devCode} ${item.devName} (${item.devType})`,
//           value: `${item.devName}`
//         });
//       });
//       // nDevList = [...new Set(nDevList)];
//       devList.value = nDevList.map(item => {
//         return {
//           label: item.label,
//           value: item.value
//         };
//       });
//       console.log("#仪器去重列表", devList);
//     }
//   });
// };

// 查询预约点击事件
const selectAppointmentClick = () => {
  queryAppointmentFormData.page = 1;
  selectByPageFunc();
};

// 分页器change事件
const paginationChange = e => {
  queryAppointmentFormData.page = e;
  selectByPageFunc();
};

// 空数据转换字符串
const notDataToStr = data => {
  let str;
  if (data != undefined && data != null) {
    str = data;
  } else {
    str = "";
  }
  return str;
};

// 分页查询预约审核列表
const selectByPageFunc = async () => {
  let data = queryAppointmentFormData;
  data.startReservationDate = data.date ? data.date[0] : "";
  data.endReservationDate = data.date ? data.date[1] : "";
  console.log("#查询", data);
  await selectByPageApi(data).then(res => {
    if (res.result == "success") {
      // 处理数据格式
      res.data.list.forEach(item => {
        // 预约化学药品名单处理
        let newChemicalDrugs = item.chemicalDrugs.split(",").map((chemical, indexC) => {
          return {
            num: indexC,
            chemicalName: chemical
          };
        });
        item.chemicalDrugs = newChemicalDrugs;

        // 学生名单处理
        let newAllStudent = item.allStudent ? item.allStudent.split(";") : [];
        if (newAllStudent.length != 0) {
          newAllStudent = newAllStudent.map((studentItem, indexS) => {
            let student = studentItem.split(",");
            return {
              num: indexS,
              studentNum: student[0],
              studentName: student[1],
              studentPhone: student[2]
            };
          });
        }
        item.allStudent = newAllStudent;
        console.log("#学生名单", newAllStudent);

        // 审核数据处理
        item.checkPeople = notDataToStr(item.checkPeople);
        item.checkTime = notDataToStr(item.checkTime);
        item.checkDesc = notDataToStr(item.checkDesc);
      });

      // 赋值
      appointList.value = res.data.list;
      tableTotal.value = res.data.total;
    }
  });
};

// init
onMounted(() => {
  selectByPageFunc();
  selectAllLabFunc();
  // selectAllDevFunc();
});
</script>

<style lang="scss" scoped>
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}
</style>
